package com.rongzhe.house.login.controller;

import com.rongzhe.house.common.cache.WebCacheUtil;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.common.utils.Base64Util;
import com.rongzhe.house.login.entity.User;
import com.rongzhe.house.login.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Chengjia
 * @date 2018/3/10 16:10
 */
@Controller
@RequestMapping("/login")
public class LoginController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private WebCacheUtil webCacheUtil;

    @RequestMapping("/logout")
    public String logout(HttpServletRequest request,HttpServletResponse response,String uri){
        request.getSession().removeAttribute(Constants.USER_LOGIN_KEY);//清除session
        webCacheUtil.init(request,response).deleteCookie(Constants.USER_LOGIN_KEY);//清楚cookie
        return "redirect:"+uri;
    }

    @RequestMapping("/index")
    public String login(){
        return "login";
    }

    @RequestMapping("/dologin")
    @ResponseBody
    public ApiResult doLogin(User user,String uri, HttpServletRequest request, HttpServletResponse response,boolean isValidate) throws Exception{
/*        String cookieValue= webCacheUtil.init(request, response).getCookieValue(Constants.REQUEST_TOKEN_KEY);
        if(null!=cookieValue&&cookieValue!=""){
            ApiResult result=new ApiResult();
            result.setCode(200);
            result.setMessage("登录成功");
            cookieValue= new String(Base64Util.decode(cookieValue),"UTF-8");
            String[] data=cookieValue.split(",");
            User u = new User();
            u.setId(Integer.valueOf(data[0]));
            u.setNickName(data[1]);
            result.setData(u);
            request.getSession().setAttribute(Constants.REQUEST_TOKEN_KEY,u);
            return result;
        }*/
        if(!isValidate){
            ApiResult result=loginService.login(user);
            if(result.getCode()==200){
                user=(User) result.getData();
                if(user.getIsRember()==1){
                    webCacheUtil.init(request, response).addCookie(Constants.USER_LOGIN_KEY, Base64Util.encode((user.getId()+","+user.getNickName()).getBytes()),60*60*24*7);
                }
                request.getSession().setAttribute(Constants.USER_LOGIN_KEY,user);
            }
            return result;
        }else{
            ApiResult result=new ApiResult();
            result.setCode(-4);
            result.setMessage("登录信息已失效,请重新登录");
            return result;
        }

    }

}
